package com.atguigu.day03;

import com.atguigu.utils.IntegerSource;
import com.atguigu.utils.IntegerStatistic;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example11 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> "int")
                .process(new Statistic())
                .print();

        env.execute();
    }

    public static class Statistic extends KeyedProcessFunction<String, Integer, IntegerStatistic> {
        // 声明值状态变量
        private ValueState<IntegerStatistic> accumulator;

        @Override
        public void open(Configuration parameters) throws Exception {
            accumulator = getRuntimeContext().getState(
                    // 状态变量的描述符，需要通过描述符去检查点文件中寻找状态变量，找到了，就读取，找不到就初始化新的
                    new ValueStateDescriptor<IntegerStatistic>(
                            "accumulator", // 状态变量的名字，名字必须是独一无二的，因为需要用这个名字来保证单例特性
                            Types.POJO(IntegerStatistic.class)
                    )
            );
        }

        @Override
        public void processElement(Integer in, Context ctx, Collector<IntegerStatistic> out) throws Exception {
            // accumulator.value()读取的是in的key对应的值状态变量
            if (accumulator.value() == null) {
                // 说明in是第一条数据
                // accumulator.update更新的是in的key对应的值状态变量
                accumulator.update(new IntegerStatistic(in, in, in, 1, in));
            } else {
                IntegerStatistic oldAccumulator = accumulator.value();
                IntegerStatistic newAccumulator = new IntegerStatistic(
                        Math.min(oldAccumulator.min, in),
                        Math.max(oldAccumulator.max, in),
                        oldAccumulator.sum + in,
                        oldAccumulator.count + 1,
                        (oldAccumulator.sum + in) / (oldAccumulator.count + 1)
                );
                accumulator.update(newAccumulator);
            }

            out.collect(accumulator.value());
        }
    }
}
